class SocketHelper < ActiveRecord::Base
  #访问socket
  def self.callSocket(cmd,name,pswd)
    begin
      streamSock = getSocket(name,pswd)
      if streamSock
        restr = getCR(streamSock,cmd,true)
        streamSock.close
      else
        restr = "连接放大器失败,或用户"+name.to_s+"已被占用!"
      end
      #closeSocket(streamSock)
      return restr
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","callSocket",e,"error")
      streamSock.close if streamSock
      return ""
    end
  end
  
  #得到socket对象
  def self.getSocket(name,pswd)
    begin
      server = Constants::SERVER_INFO
      port = Constants::SERVER_PORT
      if name==nil || name==""
        name = Constants::USERNAME
      end
      if pswd==nil || pswd==""
        pswd = Constants::PASSWORD
      end
      logger.error "################## #{server} #######################"
      logger.error "login.........."+name+" "+pswd
      
      #处理登录时非常长的0,以补位
      loginTailStr = ""
      if server.index("pek4.3322.org")
        1.upto(136) do |i|
          loginTailStr = loginTailStr + 0x00.chr    
        end
        loginFirstStr = 0x01.chr+0xA2.chr
        loginFirstStr << name
        loginFirstStr << 0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr
        loginFirstStr << pswd
        loginFirstStr << loginTailStr
        loginSecondStr = 0x01.chr+0xFE.chr+0x00.chr+0x11.chr+0x14.chr+0x00.chr+0x00.chr+0x02.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr
        loginThirdStr = 0x01.chr+0xFE.chr+0x00.chr+0x11.chr+0x14.chr+0x10.chr+0x00.chr+0x02.chr+0x0C.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x01.chr+0xFE.chr+0x00.chr+0x11.chr+0x14.chr+0x10.chr+0x00.chr+0x02.chr+0x29.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr
        #loginFourthTailStr=""
        #1.upto(61) do |i|
        #  loginFourthTailStr = loginFourthTailStr + 0x00.chr    
        #end
        #loginFourthStr = 0x01.chr+0xF9.chr+ 0x00.chr+ 0x44.chr+ 0x00.chr+ 0x01.chr+ 0x0B.chr+loginFourthTailStr 
        
        streamSock = TCPSocket::new(server, port)
        #返回信息中有10004,说明正在登录的用户名有人正在使用中.
        streamSock.send( loginFirstStr ,0)
        responseStr =  streamSock.recv( 128 )
        streamSock.send( loginSecondStr ,0)
        responseStr =  streamSock.recv( 128 )
        streamSock.send( loginThirdStr ,0)
        responseStr =  streamSock.recv( 256 )
        responseStr =  streamSock.recv( 512 )
      else
        1.upto(138) do |i|
          loginTailStr = loginTailStr + 0x00.chr    
        end
        inStr = 0x01.chr+0xA2.chr
        inStr << name
        inStr << 0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr+0x00.chr
        inStr << pswd
        inStr << loginTailStr
        
        streamSock = TCPSocket::new(server, port)
        #返回信息中有10004,说明正在登录的用户名有人正在使用中.
        streamSock.send( inStr ,0)
        responseStr =  streamSock.recv( 128 )
      end
      #puts responseStr
      if responseStr.index("10004")
        logger.error  "该用户正在被使用"
        #streamSock.close
        streamSock = nil
      elsif responseStr.index("1000") || responseStr.index("Bad file")
        logger.error  "登陆失败"
        #streamSock.close
        streamSock = nil
      else
        logger.error  "登陆成功"
      end
      return streamSock
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","getSocket",e,"error")
      streamSock.close if streamSock
      return nil
    end
  end
  
  def self.closeSocket(streamSock)
    begin
      streamSock.close if streamSock
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","closeSocket",e,"error")
    end
  end
  
  #得到命令返回结果并转码
  def self.getCR(streamSock,cmd,needRevert)
    begin
      if cmd.index(Constants::SEPARATE_KEY) #|| cmd.index("AVH/") || cmd=="pn" || cmd.index("rt")
        logger.error  "========== Socket_Helper getCR START !!!! =========="
        #logger.error streamSock
        fix_flag = true
      end
      if streamSock==nil
        return "连接放大器失败,或用户已被占用!"
      end
      cmd = cmd.gsub(/--/,"\r") #替换分隔符
      if fix_flag
        logger.error cmd
      end
      commandSubHeadStr = 0x1B.chr+0x0B.chr+0x20.chr+0x20.chr+0x00.chr+0x0F.chr+0x1E.chr
      commandTailStr = 0x20.chr+0x03.chr
      cmd = commandSubHeadStr+cmd+commandTailStr
      len = cmd.length+12
      server = Constants::SERVER_INFO
      if server.index("pek4.3322.org")
        if len>=256
          pro = len/256
          rest = len%256
          commandHeadStr = 0x01.chr+0x00.chr+pro.chr+rest.chr+0x00.chr+0x00.chr+0x00.chr+0x01.chr+0x36.chr+0x51.chr+0x70.chr+0x02.chr
        else
          commandHeadStr = 0x01.chr+0x00.chr+0x00.chr+len.chr+0x00.chr+0x00.chr+0x00.chr+0x01.chr+0x36.chr+0x51.chr+0x70.chr+0x02.chr
        end
      else
        if len>=256
          pro = len/256
          rest = len%256
          commandHeadStr = 0x01.chr+0x00.chr+pro.chr+rest.chr+0x00.chr+0x00.chr+0x00.chr+0x01.chr+0x51.chr+0x40.chr+0x70.chr+0x02.chr
        else
          commandHeadStr = 0x01.chr+0x00.chr+0x00.chr+len.chr+0x00.chr+0x00.chr+0x00.chr+0x01.chr+0x51.chr+0x40.chr+0x70.chr+0x02.chr
        end
      end
      inCStr = commandHeadStr + cmd
      
      resultStr = ""
      timeout(50) do
        streamSock.send( inCStr ,0)
        responseStr =  streamSock.recv( 2048 )
        if responseStr==nil
          logger.error " ***** Socket_Helper getCR :: 放大器没响应!!!!!!!!!!!!!!"
          if streamSock
            streamSock.close
            streamSock = nil
          end
          return "放大器没响应"
        end
        responseStr = delHeadAndTail(responseStr) #去掉头尾无用字符
        if needRevert
          resultStr = revertCN(responseStr)
        else
          resultStr = responseStr
        end
        resultStr = resultStr.gsub(/>/, "\n")
        resultStr = resultStr.gsub(/\r/, "\n")
        resultStr = resultStr.strip #去掉前后空格
      end
      if fix_flag
        logger.error "========== Socket_Helper getCR END !!!! =========="
        logger.error resultStr
      end
      if resultStr.index("- recvfrom")
        logger.error " ***** Socket_Helper getCR :: recvfrom !!!!!!!!!!!!!!"
        resultStr = "链接超时"
      end
      return resultStr
    rescue Exception => e
      logger.error " ********** Socket_Helper getCR :: e="+e.message
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","getCR",e,"error")
      streamSock.close if streamSock
      return ""
    end
  end
  
  #得到中文的拼音和ASCII码
  def self.getTransChineseName(passenger_name)
    begin
      if passenger_name && passenger_name.index(/[^\u4e00-\u9fa5]/) && passenger_name.index("/")==nil
        pinYin = ""
        transName = ""
        n = passenger_name.length/3
        for i in 0..n-1
          char = passenger_name[i*3,3]
          encodingChar = EncodingChar.find(:first,:conditions=>["cn_char=?",char])
          if encodingChar
            pinYin << encodingChar.py
            transName << encodingChar.encoding
          end
        end
        #获取前后字符
        beginStr = 0x1B.chr+0x0E.chr
        endStr = 0x1B.chr+0x0F.chr
        transName = beginStr + transName + endStr
        passenger_name = pinYin+transName
      end
      return passenger_name
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","getTransChineseName",e,"error")
      return passenger_name
    end
  end
  
  #得到中文的拼音
  def self.getPinYin(passenger_name)
    begin
      if passenger_name && passenger_name.index(/[^\u4e00-\u9fa5]/) && passenger_name.index("/")==nil
        pinYin = ""
        n = passenger_name.length/3
        for i in 0..n-1
          char = passenger_name[i*3,3]
          encodingChar = EncodingChar.find(:first,:conditions=>["cn_char=?",char])
          if encodingChar
            pinYin << encodingChar.py
          end
        end
        #获取前后字符
        passenger_name = pinYin
      end
      return passenger_name
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","getPinYin",e,"error")
      return passenger_name
    end
  end
  
  def self.revertCN(originalStr)
    begin
      if originalStr && originalStr!=""
        pi = 0 #当前要开始搜索的位置
        i = 0 #顺序,记录第几个中文串
        cnHash = Hash.new
        arr = []
        while originalStr.index((0x1B.chr+0x0E.chr),pi)
          i = i + 1
          bi = originalStr.index((0x1B.chr+0x0E.chr),pi) #开始位置
          ei = originalStr.index((0x1B.chr+0x0F.chr),pi)+1 #结束位置
          pi = bi #更新当前要开始搜索的位置
          currentCNStr = originalStr[bi..ei] #
          pureCNCodeStr = currentCNStr[2..(currentCNStr.length-3)]
          cnHash[i] = pureCNCodeStr #把纯汉字编码打入Hash
          originalStr = originalStr.gsub("#{currentCNStr}","|#{i}|") #对第i个汉字串进行替换,都替换为|i|的形式
          #同时拼了个下一步准备查数据库的长字串
          0.upto(pureCNCodeStr.length/2-1) do |j|
            value = pureCNCodeStr[j*2,2]
            if arr[0]
              arr[0] << " or encoding=?"
            else
              arr[0] = "encoding=?"
            end
            arr.push(value)
          end
        end
        #如果确实有汉字存在,扫行数据库操作查出所有相关的汉字
        if i >0
          cnDBHash = Hash.new
          encodingChars = EncodingChar.find(:all,:conditions=>arr) 
          encodingChars.each do |encodingChar|
            #logger.error encodingChar.cn_char
            cnDBHash["#{encodingChar.encoding}"] = encodingChar.cn_char
          end 
          #开始替换HASH编码为真正汉字
          1.upto(i) do |k|
            subCNStr = ""
            cnEncodedStr = cnHash[k]
            0.upto(cnEncodedStr.length/2-1) do |l|
              subCNStr << cnDBHash["#{cnEncodedStr[l*2,2]}"]
            end
            cnHash[k]=subCNStr
          end
          #开始把HASH中的真正汉字全换入原始串中.
          1.upto(i) do |m|
            originalStr = originalStr.gsub("|#{m}|","#{cnHash[m]}")
          end
        end
      end
      return originalStr
      #以上主要是处理了汉字所在的位置,然后根据位置存储了相应的汉字编码.
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","revertCN",e,"error")
      return originalStr
    end
  end

  def self.delHeadAndTail(originalStr)
    begin
      if originalStr && originalStr!=""
        #去掉前面的头
        headStr = 0x1b.chr+0x0b.chr
        if originalStr.index(headStr) && originalStr.index(headStr)==12
          originalStr = originalStr[19..-1]
        else
          originalStr = originalStr[13..-1]
        end
        #去掉后面的尾
        endStr = 0x20.chr+0x20.chr+0x0D.chr+0x1E.chr+0x1B.chr+0x62.chr+0x03.chr
        if originalStr.index(endStr) #&& originalStr.length-originalStr.index(endStr)<10
          originalStr = originalStr[0,originalStr.index(endStr)]
        else
          originalStr = originalStr[0..-4]
        end
      end
      return originalStr
    rescue Exception => e
      CommonHelper.infoLogger(nil,nil,"Socket_Helper","delHeadAndTail",e,"error")
      return originalStr
    end
  end
end